﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace CNKI.TPI.Web.Base
{
    public class SerializeHelper
    {
        /// <summary>
        /// 对类FGTWeb.Model.M_Login进行二进制序列化成一个字符串
        /// </summary>
        /// <returns>序列化代码</returns>
        public static string BinarySerialize(Object obj)
        {
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream mStream = new MemoryStream();
            ser.Serialize(mStream, obj);
            byte[] buf = mStream.ToArray();
            mStream.Close();
            buf = Compress(buf);
            return Convert.ToBase64String(buf);
        }
        /// <summary>
        /// 将从Cookie中取出的字符串反序列化成一个FGTWeb.Model.M_Login类
        /// </summary>
        /// <param name="binary"></param>
        /// <returns></returns>
        public static T BinaryDeSerialize<T>(string content)
        {
            byte[] binary = Convert.FromBase64String(content);
            binary = Decompress(binary);
            BinaryFormatter ser = new BinaryFormatter();
            MemoryStream mStream = new MemoryStream(binary);
            T o = (T)ser.Deserialize(mStream);
            mStream.Close();
            return o;
        }

        public static T Deserialize<T>(string json)
        {
            T obj = default(T);
            try
            { 
                obj = JsonConvert.DeserializeObject<T>(json);
            }
            catch(Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return obj;
        }

        public static string Serialize(Object obj)
        {
            string result = "";
            try
            {
                if (obj.GetType() == typeof(DataTable) || obj.GetType() == typeof(Dictionary<string, int>))
                {
                    result = JsonConvert.SerializeObject(obj, new DataTableConverter());
                }
                else
                {
                    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                    using (MemoryStream stream = new MemoryStream())
                    {
                        serializer.WriteObject(stream, obj);
                        result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                    }
                }
                
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }
            return result;
        }

        /// <summary>  
        /// 字符串压缩  
        /// </summary>  
        /// <param name="strSource"></param>  
        /// <returns></returns>  
        private static byte[] Compress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true);
                zip.Write(data, 0, data.Length);
                zip.Close();
                byte[] buffer = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(buffer, 0, buffer.Length);
                ms.Close();
                return buffer;

            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }

        /// <summary>  
        /// 字符串解压缩  
        /// </summary>  
        /// <param name="strSource"></param>  
        /// <returns></returns>  
        private static byte[] Decompress(byte[] data)
        {
            try
            {
                MemoryStream ms = new MemoryStream(data);
                GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true);
                MemoryStream msreader = new MemoryStream();
                byte[] buffer = new byte[0x1000];
                while (true)
                {
                    int reader = zip.Read(buffer, 0, buffer.Length);
                    if (reader <= 0)
                    {
                        break;
                    }
                    msreader.Write(buffer, 0, reader);
                }
                zip.Close();
                ms.Close();
                msreader.Position = 0;
                buffer = msreader.ToArray();
                msreader.Close();
                return buffer;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
    }
}
